package com.lp.service.impl;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lp.bo.UserAccountInfoBO;
import com.lp.bo.UserInfoBO;
import com.lp.cache.CacheName;
import com.lp.cache.ProCacheUtil;
import com.lp.cfg.ProConfig;
import com.lp.common.Code;
import com.lp.service.UserService;
import com.lp.service.base.MailService;
import com.lp.util.CommonUtil;
import com.lp.util.DateUtils;
import com.lp.util.ObjectUtil;

@Service
public class UserServiceImpl extends BaseServiceImpl  implements UserService  {

	@Autowired
	private MailService mailService;
	
	@Override
	public Map<String, Object> sendSecurityCode(String name) {
		Map<String, Object> resultMap = getResultMap();
		try {
			// 检索当前用户存在与否
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setEmail(name);
			UserInfoBO user = (UserInfoBO) dao.selectOne("UserInfo.selectOne", userInfoBO);
			if (user == null) {
				return putStatusCode(resultMap, Code.ResponseCode.UserInfo.USER_NOT_EXISTS);
			}
			// 邮箱验证码
			String uuid = CommonUtil.UUIDString.getEncodeUUIDString();
			// 更新用户
			userInfoBO.setValidate_code(uuid);
			userInfoBO.setValidate_time(new Date());
			userInfoBO.setId(user.getId());
			dao.update("UserInfo.update", userInfoBO);
			// 发邮件
			Map<String, Object> mail = new HashMap<String, Object>();
			mail.put("name", name);
			mail.put("email", name);
			mail.put("url",ProConfig.LOCAL_DOMAIN + MessageFormat.format("/service/mail/{0}", new Object[] { 2 + uuid }));
			mailService.send(name, ProConfig.PROJECT_NAME + "用户激活邮件", "tpl/vm/user_register_activation", mail);
		} catch (Exception e) {
			super.exception(e, resultMap, name);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> userRegisterByPhone(UserInfoBO user) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setName(user.getPhone());

			userInfoBO = dao.selectOne("UserInfo.selectOne", userInfoBO);
			if(ObjectUtil.isNotEmpty(userInfoBO)){
				putStatusCode(resultMap, Code.ResponseCode.UserInfo.PHONE_EXIST);
			}else{
				user.setPhone(user.getPhone());
				user.setName(user.getPhone());
				user.setUser_key(ObjectUtil.UUIDString.getUUIDString());
				user.setStatus(Code.UserStatus.NORMAL);
				// 注册为普通用户
				user.setType(Code.UserType.Normal);
				user.setValidate_time(new Date());
				dao.insert("UserInfo.insert", user);
				
				// 添加用户账户表
				UserAccountInfoBO userAccountBo = new UserAccountInfoBO();
				userAccountBo.setUser_id(user.getId());
				Integer j = dao.insert("UserAccountInfo.insertSimple", userAccountBo);
				if( j> 0){
					ProCacheUtil.addCache(CacheName.USERACCOUNT_ID, userAccountBo.getUser_id().toString() ,userAccountBo);
				}
				
				
				// ---
				putData(resultMap, user);
			}
		} catch (Exception e) {
			super.exception(e, resultMap, user);
		}
		return resultMap;
	}
	
	@Override
	public Map<String, Object> userRegister(UserInfoBO user) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setEmail(user.getName());
			userInfoBO = dao.selectOne("UserInfo.selectOne", userInfoBO);
			if(ObjectUtil.isNotEmpty(userInfoBO)){
				if(userInfoBO.getStatus() == Code.UserStatus.UN_ACTIVED){
					user.setId(userInfoBO.getId());
					user.setEmail(user.getName());
					user.setValidate_code( ObjectUtil.UUIDString.getUUIDString());
					user.setValidate_time(new Date());
					user.setMtime(new Date()); ;
					Integer i = dao.update("UserInfo.update", user);
					if( ObjectUtil.isIntegerOverZero(i) ){
						// 发邮件 待激活用户
						Map<String, Object> mail = new HashMap<String, Object>();
						mail.put("name", user.getEmail());
						mail.put("email", user.getEmail());
						mail.put("url",ProConfig.LOCAL_DOMAIN + MessageFormat.format("/service/mail/{0}", new Object[] {  user.getValidate_code() }));
						mailService.send(user.getEmail(), ProConfig.PROJECT_NAME + "用户激活邮件", "tpl/vm/user_register_activation.vm", mail);					
					}
					putData(resultMap, userInfoBO);
				}else{
					return putStatusCode(resultMap, Code.ResponseCode.UserInfo.USER_EXIST);					
				}
			}else{
				user.setEmail(user.getName());
				user.setValidate_code( ObjectUtil.UUIDString.getUUIDString());
				user.setUser_key(ObjectUtil.UUIDString.getUUIDString());
				user.setStatus(Code.UserStatus.UN_ACTIVED);
				// 注册只有普通用户
				user.setType(Code.UserType.Normal);
				user.setValidate_time(new Date());
				user.setMtime(new Date());
				Integer i = dao.insert("UserInfo.insert", user);
				
				UserAccountInfoBO userAccountBo = new UserAccountInfoBO();
				userAccountBo.setUser_id(user.getId());
				Integer j = dao.insert("UserAccountInfo.insertSimple", userAccountBo);
				if( j> 0){
					ProCacheUtil.addCache(CacheName.USERACCOUNT_ID, userAccountBo.getUser_id().toString() ,userAccountBo);
				}
				
				if( ObjectUtil.isIntegerOverZero(i) ){
					// 发邮件 待激活用户
					Map<String, Object> mail = new HashMap<String, Object>();
					mail.put("name", user.getEmail());
					mail.put("email", user.getEmail());
					mail.put("url",ProConfig.LOCAL_DOMAIN + MessageFormat.format("/service/mail/{0}", new Object[] {  user.getValidate_code() }));
					mailService.send(user.getEmail(), ProConfig.PROJECT_NAME + "用户激活邮件", "tpl/vm/user_register_activation.vm", mail);					
				}
				putData(resultMap, user);
			}
		} catch (Exception e) {
			super.exception(e, resultMap, user);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> validateCode(String validatecode) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setValidate_code(validatecode);
			userInfoBO =  dao.selectOne("UserInfo.selectOne", userInfoBO);
			if(ObjectUtil.isNotEmpty(userInfoBO)){
				if(userInfoBO.getStatus() == Code.UserStatus.UN_ACTIVED){
					if(DateUtils.getTimeBeforetimes(userInfoBO.getValidate_time(), 15)){
						UserInfoBO user = new UserInfoBO();
						user.setId(userInfoBO.getId());
						user.setStatus(Code.UserStatus.NORMAL);
						Integer num = dao.update("UserInfo.update", user);
						if(!ObjectUtil.isIntegerOverZero(num)){
							putStatusCode(resultMap, Code.ResponseCode.SystemCode.ERROR);
						}
					}else{
						putStatusCode(resultMap, Code.ResponseCode.SystemCode.ACTIVE_CODE_OVERDUE);
					}
				}else{
					putStatusCode(resultMap, Code.ResponseCode.SystemCode.ACTIVED);
				}
			}else{
				// 当前激活码不存在 
				putStatusCode(resultMap, Code.ResponseCode.SystemCode.NO_ACTIVE_CODE);
			}
		} catch (Exception e) {
			super.exception(e, resultMap, validatecode);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> resetPassword(UserInfoBO user) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setEmail(user.getEmail());
			userInfoBO = dao.selectOne("UserInfo.selectOne", userInfoBO);
			if(ObjectUtil.isNotEmpty(userInfoBO)){
				user.setId(userInfoBO.getId());
				user.setValidate_code( ObjectUtil.UUIDString.getUUIDString());
				user.setValidate_time(new Date());
				Integer i = dao.update("UserInfo.update", user);
				if( ObjectUtil.isIntegerOverZero(i) ){
					// 发邮件 重置密码
					Map<String, Object> mail = new HashMap<String, Object>();
					mail.put("name", user.getEmail());
					mail.put("email", user.getEmail());
					mail.put("url",ProConfig.LOCAL_DOMAIN + MessageFormat.format("/service/mail/reset/password/{0}", new Object[] { user.getValidate_code() }));
					mailService.send(user.getEmail(), ProConfig.PROJECT_NAME + "重置密码邮件", "tpl/vm/user_reset_password.vm", mail);
				}
			}else{
				putStatusCode(resultMap, Code.ResponseCode.UserInfo.USER_NOT_EXISTS);
			}
		} catch (Exception e) {
			super.exception(e, resultMap, user);
		}
		return resultMap;
	}

	@Override
	public Map<String, Object> mailValidatePassword(String validatecode) {
		Map<String, Object> resultMap = getResultMap();
		try {
			UserInfoBO userInfoBO = new UserInfoBO();
			userInfoBO.setValidate_code(validatecode);
			userInfoBO =  dao.selectOne("UserInfo.selectOne", userInfoBO);
			if(!ObjectUtil.isNotEmpty(userInfoBO)){
				putStatusMsg(resultMap, "验证码不存在");
			}else{
				if(DateUtils.getTimeBeforetimes(userInfoBO.getValidate_time(), 15)){
					putData(resultMap, userInfoBO);					
				}else{
					// 验证码已过期
					putStatusCode(resultMap, Code.ResponseCode.SystemCode.ACTIVE_CODE_OVERDUE);
				}
			}
		} catch (Exception e) {
			super.exception(e, resultMap, validatecode);
		}
		return resultMap;
	}
	
}
